/**
 * 获取URL参数
 * @param {Object} obj
 * @param {String} [url]
 */
export function toQuery(name) {
    var url = window.location.search
    if (url.indexOf('?') < 0) return name ? '' : {}
    var dataStr = url.split('?')[1],
        dataArr = dataStr.split('&'),
        dataObj = {}

    for (var i = 0; i < dataArr.length; i++) {
        var a = dataArr[i].split('=')
        dataObj[a[0]] = decodeURIComponent(a[1])
    }

    if (name) return dataObj[name]

    return dataObj
}

/**
 * 对象转URL参数
 * @param {Object} obj
 * @param {String} [url]
 */
export function toParam(data, url) {
    var temp = []
    for (const key in data) {
        if (data[key] != undefined) temp.push(`${key}=${data[key]}`)
    }

    const param = temp.length ? temp.join('&') : ''

    if (url) {
        if (temp.length) url += url.indexOf('?') == -1 ? '?' : '&'

        return url + param
    } else {
        return param
    }
}

export default {
    toQuery,
    toParam,
}
